#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>

#define START_CHAR 'A'

static int sort(char *, char *, int, GtkTextBuffer *);
static int add_str(char *, int, char);
static int clr_str(char *, int, int);

/*做一些预处理，然后调用sort()*/
int deal(int num, GtkTextBuffer *text){
	char *ch = (char *)malloc(sizeof(char) *num + 1);
	char *head = (char *)malloc(sizeof(char) *num *2);
	char *tail = (char *)malloc(sizeof(char) *num *2);

	bzero (head, sizeof(char) *num *2);
	bzero (tail, sizeof(char) *num *2);

	int i = 1;
	for(ch[0] = START_CHAR; i < num; i++)
		ch[i] = ch[i-1] + 1;

	sort (head, ch, num, text);

	free (ch);
	free (head);
	free (tail);
}

/*因为有“=”号这特殊情况，交换顺序的一样的，所以检查是否保持递增的顺序*/
static int check(char *head, char ch, int size){
	int i = 0;
	if(head != NULL){
		while(head[i] != '\0' && i < size)
			i++;
		if (head[i-2] >= ch && head[i-1] == '=')
			return 0;
	}
	return 1;	
}

/*递归处理。*/
static int sort(char *head, char *ch, int num, GtkTextBuffer *text){
	char choose = '\0';
	int i;

	int count = 0, j;
        for(j = 0; j < num; j++)
		if(ch[j] != '\0'){
			choose = ch[j];
			count++;
		}
        if(count == 1 && check(head, choose, sizeof(char) *num *2)){
		sort_prin (head, choose, sizeof(char) *num *2, text);
		return 0;
	}

	for(i = 0; i < num; i++){
		if(ch[i] != '\0'){
			choose = ch[i];
			ch[i] = '\0';
			if(check(head, choose, sizeof(char) *num *2)){
				add_str (head, sizeof(char) *num *2, choose);
				add_str (head, sizeof(char) *num *2, '<');
				sort (head, ch, num, text);
				clr_str (head, sizeof(char) *num *2, 2);
			
				add_str (head, sizeof(char) *num *2, choose);
                               	add_str (head, sizeof(char) *num *2, '=');
                               	sort (head, ch, num, text);
                               	clr_str (head, sizeof(char) *num *2, 2);
			}
			ch[choose-START_CHAR] = choose;
			choose = '\0';
			}
	}
}

static int add_str(char *str, int size, char ch){
	int i;
	for(i = 0; i < size; i++)
		if(str[i] == '\0'){
			str[i] = ch;
			return 0;
		}
	return 0;
}

static int clr_str(char *str, int size, int count){
	int i;
	for(i = size-1; i >= 0; i--){
		if(str[i] != '\0' && count > 0){
			str[i] = '\0';
			count--;
		}
		else
			if(count == 0)
				return 0;
	}
}
